package com.java.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import com.java.mapper.AdminMapper;
import com.java.mapper.LogMapper;
import com.java.mapper.StudentMapper;
import com.java.mapper.TeacherMapper;
import com.java.po.Admin;
import com.java.po.Student;
import com.java.po.Teacher;
import com.java.util.EmailUtil;
import com.java.util.LogUtil;
import com.java.util.MD5Util;

@Controller
@RequestMapping("/report")
@Scope("prototype")
public class LoginController {

	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private TeacherMapper teacherMapper;

	@Autowired
	private LogMapper logMapper;

	// 构造器
	private Student student = null;
	private Admin admin = null;
	private Teacher teacher = null;
	private LogUtil logUtil = null;

	public LoginController() {
		logUtil = new LogUtil();
		student = new Student();
		admin = new Admin();
		teacher = new Teacher();

	}

	/**
	 * 获取seission值-student
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/findlogin", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public Map<String, Object> onSession(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Student student = (Student) request.getSession().getAttribute("student");
		Student selectByPrimaryKey = studentMapper.selectByPrimaryKey(student.getId());
		map.put("student", selectByPrimaryKey);
		return map;
	}

	/**
	 * 获取seission值-admin
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/findloginA", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	public Map<String, Object> onSessionA(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Admin selectByPrimaryKey = adminMapper.selectByPrimaryKey(admin.getId());
		map.put("admin", selectByPrimaryKey);
		return map;
	}

	/**
	 * 用户登陆
	 * 
	 * @param username
	 * @param studentid
	 * @param password
	 * @param code
	 * @param logintype
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	private Map<String, Object> LoginTo(@RequestParam(name = "username", defaultValue = "") String userName,
			@RequestParam(name = "studentid", defaultValue = "") String studentid,
			@RequestParam(name = "password", defaultValue = "") String password,
			@RequestParam(name = "code", defaultValue = "") String code,
			@RequestParam(name = "logintype", defaultValue = "") String logintype, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String username = new String(userName.getBytes("ISO-8859-1"), "utf-8");
		try {
			Object attribute = request.getSession().getAttribute("accountLoginCpacha");
			if (attribute == null) {
				map.put("status", 0);
				map.put("msg", "验证码过期，请刷新！");
				return map;
			}
			if (!code.equalsIgnoreCase(attribute.toString())) {
				map.put("status", 0);
				map.put("msg", "验证码错误！");
				return map;
			}
			char type = logintype.charAt(1);
			if (type == 's') {// 学生登录
				if (studentid.trim().equals("") || studentid.equals("") || studentid == null) {
					map.put("status", 0);
					map.put("msg", "请正确输入学号！");
					return map;
				}
				student.setUsername(username);
				student.setStudentid(Integer.parseInt(studentid));
				student.setPassword(MD5Util.md5Password(password));
				Student selectOne = studentMapper.selectOne(student);
				if (selectOne != null) {
					map.put("status", 1);
					map.put("type", 1);
					map.put("msg", "登陆成功！");
					request.getSession().setAttribute("student", selectOne);
					logMapper.insertLog(selectOne.getUsername(), logUtil.getLOGIN(), logUtil.getSUCCESS());
				} else {
					map.put("status", 0);
					map.put("msg", "用户不存在,或者密码错误！");
					return map;
				}
			} else if (type == 't') {// 教师登陆
				teacher.setUsername(username);
				teacher.setPassword(MD5Util.md5Password(password));
				Teacher selectOne = teacherMapper.selectOne(teacher);
				if (selectOne != null) {
					map.put("status", 1);
					map.put("type", 2);
					map.put("msg", "登陆成功！");
					request.getSession().setAttribute("teacher", selectOne);
					logMapper.insertLog(selectOne.getUsername(), logUtil.getLOGIN(), logUtil.getSUCCESS());
				} else {
					map.put("status", 0);
					map.put("msg", "用户不存在,或者密码错误！");
					return map;
				}
			} else {// 管理员登陆
				admin.setUsername(username);
				admin.setPassword(MD5Util.md5Password(password));
				Admin selectOne = adminMapper.selectOne(admin);
				if (selectOne != null) {
					map.put("status", 1);
					map.put("type", 3);
					map.put("msg", "登陆成功！");
					request.getSession().setAttribute("admin", selectOne);
					logMapper.insertLog(selectOne.getUsername(), logUtil.getLOGIN(), logUtil.getSUCCESS());
				} else {
					map.put("status", 0);
					map.put("msg", "用户不存在,或者密码错误！");
					return map;
				}
			}
		} catch (Exception e) {
			logMapper.insertLog("用户", logUtil.getLOGIN(), logUtil.getERROR());
			map.put("status", 0);
			map.put("msg", "发送未知错误，请联系管理员！");
			e.printStackTrace();
		}

		return map;

	}

	/**
	 * 学生报到
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
	@ResponseBody
	private Map<String, Object> ReportTo(HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String userName = request.getParameter("username");
		String username = new String(userName.getBytes("ISO-8859-1"), "utf-8");
		String studentid = request.getParameter("studentid");
		String code = request.getParameter("code");
		// System.out.println(username + studentid);
		Object attribute = request.getSession().getAttribute("accountLoginCpacha");
		if (attribute == null) {
			map.put("status", 0);
			map.put("msg", "验证码过期，请刷新！");
			return map;
		}
		if (!code.equalsIgnoreCase(attribute.toString())) {
			map.put("status", 0);
			map.put("msg", "验证码错误！");
			return map;
		}
		Example example = new Example(Student.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("username", username);
		criteria.andEqualTo("studentid", Integer.parseInt(studentid));
		int count = studentMapper.selectCountByExample(example);
		if (count == 1) {
			student.setStudentid(Integer.parseInt(studentid));
			Student selectOne = studentMapper.selectOne(student);
			if (selectOne.getPassword() == null) {
				map.put("status", 1);
				map.put("id", selectOne.getId());
				map.put("msg", "请完善资料！");
				logMapper.insertLog(selectOne.getUsername(), logUtil.getLOGIN() + "转" + logUtil.getREGISTER(),
						logUtil.getSUCCESS());
			} else {
				map.put("status", 2);
				map.put("msg", "你已经报到过，请使用密码登陆！");
				return map;
			}
		} else {
			map.put("status", 0);
			map.put("msg", "用户不存在！");
			return map;
		}
		return map;
	}

	/**
	 * 学生完善信息（更新数据）
	 * 
	 * @param student
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	@ResponseBody
	private Map<String, Object> update(@RequestBody Student student) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			student.setPassword(MD5Util.md5Password(student.getPassword()));
			student.setReporttotime(new Date());
			student.setUpdatetime(new Date());
			if (student.getPhone().length() != 11) {
				map.put("status", 0);
				map.put("msg", "输入手机号有误，请重新输入！");
				return map;
			}
			if (student.getQq().length() < 5) {
				map.put("status", 0);
				map.put("msg", "输入QQ号有误，请重新输入！");
				return map;
			}
			int result = studentMapper.updateByPrimaryKeySelective(student);
			if (result > 0) {
				map.put("status", 1);
				map.put("msg", "完善成功，请使用密码进行登录！");
				logMapper.insertLog(student.getUsername(), logUtil.getREGISTER(), logUtil.getSUCCESS());
			} else {
				map.put("status", 0);
				map.put("msg", "完善信息失败，请联系管理员！");
				return map;
			}
		} catch (Exception e) {
			logMapper.insertLog(student.getUsername(), logUtil.getREGISTER(), logUtil.getERROR());
			map.put("status", 0);
			map.put("msg", "发送未知错误，请联系管理员！");
			e.printStackTrace();
		}
		return map;

	}

	/**
	 * 密码重置
	 * 
	 * @param username
	 * @param studentid
	 * @param password
	 * @param qq
	 * @param uptype
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uppwd", method = RequestMethod.PUT)
	@ResponseBody
	private Map<String, Object> upatepwd(@RequestBody HashMap<String, String> hashMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		EmailUtil emailUtil = new EmailUtil();
		logUtil.setDowhere("密码重置");
		try {
			String username = hashMap.get("username");
			String phone = hashMap.get("phone");
			String qq = hashMap.get("qq");
			String upType = hashMap.get("upType");
			System.out.println(qq);
			if (phone.length() != 11) {
				map.put("status", 0);
				map.put("msg", "输入手机号有误，请重新输入！");
				return map;
			}
			if (qq.length() < 5) {
				map.put("status", 0);
				map.put("msg", "输入QQ号有误，请重新输入！");
				return map;
			}
			if (upType.equals("s")) {
				student.setUsername(username);
				student.setPhone(phone);
				student.setQq(qq);
				Student selectOneS = studentMapper.selectOne(student);
				System.out.println(selectOneS);
				if (selectOneS != null) {
					String QQEmail = qq + "@qq.com";
					String newPwdS = emailUtil.newPwd();
					emailUtil.doSendHtmlEmail("新生报到系统重置密码", "您的密码重置为：" + emailUtil.text(newPwdS) + ",为账号安全尽快修改改密码。",
							QQEmail);
					selectOneS.setUpdatetime(new Date());
					selectOneS.setPassword(MD5Util.md5Password(newPwdS));
					studentMapper.updateByPrimaryKeySelective(selectOneS);
					map.put("status", 1);
					map.put("msg", "重置成功，请通过邮箱查收！");
					logMapper.insertLog(selectOneS.getUsername(), logUtil.getDowhere(), logUtil.getSUCCESS());
				} else {
					map.put("status", 0);
					map.put("msg", "用户不存在或其他信息填写有误，请重新输入！");
					return map;
				}
			} else {
				map.put("status", 1);
				map.put("msg", "成功！");
			}
		} catch (Exception e) {
			logMapper.insertLog("用户", logUtil.getDowhere(), logUtil.getERROR());
			map.put("status", 0);
			map.put("msg", "发送未知错误，请联系管理员！");
			e.printStackTrace();
		}

		return map;
	}

}
